package com.securityLearn.sessionAuth.controller;

import com.securityLearn.sessionAuth.entity.UserDto;
import com.securityLearn.sessionAuth.service.AuthenticationService;
import com.securityLearn.sessionAuth.service.request.AuthenticationRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    private AuthenticationService authenticationService;

    /**
     * 登录页
     *
     * @return
     */
    @RequestMapping("/")
    public ModelAndView toLogin() {
        return new ModelAndView("login");
    }

    /**
     * 登录
     *
     * @param user
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(AuthenticationRequest user, HttpSession session) {
        // 认证用户
        UserDto resUser = authenticationService.authentication(user);
        // 存放session
        session.setAttribute(UserDto.SESSION_USER_KEY, resUser);
        return resUser.getFullName() + " 登录成功";
    }

    /**
     * 退出
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "退出成功";
    }

    /**
     * 测试资源1
     *
     * @param session
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=UTF-8"})
    public String r1(HttpSession session) {
        String fullName = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullName = ((UserDto) userObj).getFullName();
        } else {
            fullName = "匿名";
        }
        return fullName + " 访问资源1";
    }

    /**
     * 测试资源2
     *
     * @param session
     * @return
     */
    @ResponseBody
    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=UTF-8"})
    public String r2(HttpSession session) {
        String fullName = null;
        Object userObj = session.getAttribute(UserDto.SESSION_USER_KEY);
        if (userObj != null) {
            fullName = ((UserDto) userObj).getFullName();
        } else {
            fullName = "匿名";
        }
        return fullName + " 访问资源2";
    }
}
